<script lang="ts" setup>
import { useToast } from 'wot-design-uni'
import { uploadTempFileUrl } from '@/api/common'
import { getAccessToken } from '@/utils/auth'
import {completeRepair} from '@/api/order'

defineOptions({ name: 'PopCertificateForm' })
const emit = defineEmits(['refresh'])
const toast = useToast()
const show = ref(false)
const rowData = ref(null)
const form_ref = ref()
const model = reactive<{
  fileList: Array<any>
  completionDesc: string
}>({
  fileList: [],
  completionDesc: '',
})
const rules = {
  completionDesc: [
    {
      required: true,
      message: '请输入完工描述',
      // validator: (value) => {
      //   if (value && value.length > 6) {
      //     return Promise.resolve()
      //   }
      //   else {
      //     return Promise.reject('请输入完工描述')
      //   }
      // },
    },
  ],
  fileList: [
    {
      required: false,
      message: '请上传完工图片',
      validator: (value) => {
        if (Array.isArray(value) && value.length) {
          return Promise.resolve()
        }
        else {
          return Promise.reject()
        }
      },
    },
  ],
}
const open = (row) => {
  show.value = true
  rowData.value = row
}

const handleClose = () => {
  show.value = false
}
const submit = () => {
  form_ref.value.validate().then(({ valid, errors }) => {
    if (valid) {
      toast.success('校验通过')
    }
  })
}
const customUpload = (file, formData, options) => {
  const uploadTask = uni.uploadFile({
    url: uploadTempFileUrl,
    header: {
      Authorization: `Bearer ${getAccessToken()}`,
    },
    name: options.name,
    fileName: options.name,
    fileType: options.fileType,
    formData,
    filePath: file.url,
    success(res) {
      if (res.statusCode === options.statusCode) {
        options.onSuccess(res, file, formData)
      }
      else {
        options.onError({ ...res, errMsg: res.errMsg || '' }, file, formData)
      }
    },
    fail(err) {
      // 设置上传失败
      options.onError(err, file, formData)
    },
  })
  // 设置当前文件加载的百分比
  uploadTask.onProgressUpdate((res) => {
    options.onProgress(res, file)
  })
}

const handleSubmit = () => {
  form_ref.value.validate().then(async ({ valid, errors }) => {
    if (valid) {
      const {orderId} = rowData.value
      const completionPhotoUrl = model.fileList.map(item =>{
        const res = JSON.parse(item.response)
        return res.data
      }).join(',')
      const res = await completeRepair({
        orderId,
        completionPhotoUrl,
        completionDesc: model.completionDesc,
      })
      if(res.code === 0){
        toast.success('提交成功！')
        emit('refresh')
        setTimeout(() => {
          handleClose()
        }, 500);
      }else{
        toast.error('提交失败！')
      }
    }
  })
}

defineExpose({
  open,
})
</script>

<template>
  <JediPagePop v-model="show" title="完成修理" @close="handleClose">
    <view>
      <wd-form ref="form_ref" :model="model" :rules="rules">
        <wd-cell-group border>
          <wd-textarea
            v-model="model.completionDesc"
            type="textarea"
            :maxlength="200"
            show-word-limit
            placeholder="请输入完工总结"
            clearable
            prop="completionDesc"
          />
          <wd-cell title="" title-width="0" prop="fileList" custom-class="noTitle">
            <wd-upload v-model:file-list="model.fileList" :limit="6" :upload-method="customUpload" />
          </wd-cell>
        </wd-cell-group>
        <wd-cell title-width="0px">
          <view class="footer">
            <wd-button block size="large" @click="handleSubmit">
              提交完工
            </wd-button>
          </view>
        </wd-cell>
      </wd-form>
    </view>
  </JediPagePop>
</template>
